package com.yn.iotxiao.controller.User;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yn.iotxiao.Utils.*;
import com.yn.iotxiao.authorize.Authorize;
import com.yn.iotxiao.model.Hik.HikUser;
import com.yn.iotxiao.request.PageRequest;
import com.yn.iotxiao.response.ErrorResult;
import com.yn.iotxiao.response.ResponseResult;
import com.yn.iotxiao.sql.entity.Device.DeviceInfo;
import com.yn.iotxiao.sql.entity.Group.GroupInfo;
import com.yn.iotxiao.sql.entity.User.TeacherInfo;
import com.yn.iotxiao.sql.entity.User.User;
import com.yn.iotxiao.sql.mapper.GroupMapper;
import com.yn.iotxiao.sql.services.Group.GroupService;
import com.yn.iotxiao.sql.services.User.TeacherService;
import com.yn.iotxiao.sql.services.UserService;
import io.micrometer.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@RequestMapping("/teacher")
@Slf4j
@RestController
@ResponseResult
public class TeacherController {

    @Autowired
    TeacherService service;
    @Autowired
    UserService uService;
    @Autowired
    GroupService gService;

    @PutMapping
    @Authorize
    public Object putTeacher(@Validated @RequestBody TeacherInfo request) throws Exception {

        var user = uService.getWithUid(request.getGh());

        if (user != null && !"teacher".equals(user.getType())) {
            throw new Exception("当前工号用户已经存在且不是教师用户，请检查");
        }
        String loginId = request.getPhone();
        if (StringUtils.isBlank(loginId)) {
            loginId = request.getGh();
        }
        int result = uService.insert(new User(request.getGh(),request.getName(),loginId,loginId,
                SecretUtil.md5(loginId),"teacher",false));
        if (result < 0) {
            throw new Exception("写入用户失败");
        }
         result = service.insert(request);
        if (result > 0) {
            //写入权限组==》
            GroupInfo group = gService.getWithType("10");
            log.info("group:" + JSONUtil.toJsonStr(group));
            if (group != null && !StringUtils.isBlank(group.getId())) {

                //写入设备
                List<DeviceInfo> devices = gService.getGroupDevices(group.getId());
                String deviceIds = "";
                for (var device :
                        devices) {
                    //调用接口写入设备人员
                    JSONObject body = JsonHelper.create("UserInfo",new HikUser(request.getGh(),request.getName()));

                    HikHttpUtil httpUtil = new HikHttpUtil(device.getIp(),"/ISAPI/AccessControl/UserInfo/SetUp",
                            device.getLoginId(),device.getPassword());
                    JSONObject response =  httpUtil.doBodyPut(body);
                    if("1".equals(JsonHelper.getValue(response,"statusCode"))) {
                        deviceIds += device.getDeviceid() + ",";
                    }
                    log.error("返回信息：" + response.toString());

                }
                log.info("deviceIds:" + deviceIds);
                //写入权限组
                result = gService.putUser(request.getGh(),"teacher",group.getId(),deviceIds);
                log.info("result:" + result);

            }
            return  "保存成功";
        }else {
            uService.delete(request.getGh());
        }
       throw new Exception("保存失败");
    }

    @PostMapping("/list")
    @Authorize
    public Object getList(@RequestBody PageRequest request) {

        List<TeacherInfo> list = service.getListPage(request.getSearchKey(),request.getPage(),request.getPageSize());
        int total = service.getTotal(request.getSearchKey());

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list",list);
        jsonObject.put("total",total);
        return  jsonObject;
    }

    @DeleteMapping("/{gh}")
    @Authorize
    public String deleteWithGh(@PathVariable String gh) throws Exception{
        int result = service.deleteWithKey(gh);
        if (result > 0) {
            uService.delete(gh);
            return "删除成功";
        }
        throw new Exception("删除失败");
    }

    @PutMapping("/list")
    @Authorize
    public Object putList(@RequestBody List<com.alibaba.fastjson.JSONObject> list) throws Exception{
        if (list == null || list.size() == 0) {
            throw new Exception("未获取到数据");
        }

        List<TeacherInfo> inserts = new ArrayList<>();
        JSONArray error = new JSONArray();
        JSONArray success = new JSONArray();
        List<User> users = new ArrayList<>();
        for (com.alibaba.fastjson.JSONObject data : list) {
            String name = JsonHelper.getValue(data, "姓名");
            if (name.isEmpty()) {
                data.put("mark", "姓名为空");
                error.add(data);
                continue;
            }
            String gh = JsonHelper.getValue(data, "工号");
            if (gh.isEmpty()) {
                data.put("mark", "工号为空");
                error.add(data);
                continue;
            }

            String phone =JsonHelper.getValue (data, "手机号");
//            if (month.isEmpty()) {
//                data.put("mark", "出版月份为空");
//                error.add(data);
//                continue;
//            }
            //筛选是否已经录入过
            User user = uService.getWithUid(gh);
            if (user != null && StringUtils.isBlank(user.getUid())) {
                data.put("mark", "当前工号已经录入过");
                error.add(data);
                continue;
            }

            data.put("mark", "录入成功");
            success.add(data);
            //其他的数据写入
            TeacherInfo teacherInfo = new TeacherInfo();
            teacherInfo.setName(name);
            teacherInfo.setGh(gh);
            teacherInfo.setPhone(phone);

            inserts.add(teacherInfo);
            String loginId = phone;
            if (StringUtils.isBlank(loginId)) {
                loginId = gh;
            }
            users.add(new User(gh,name,loginId,loginId,
                    SecretUtil.md5(loginId),"teacher",false));
        }
        log.info("inserts:" + inserts.size());

        if (inserts.size() > 0) {
            uService.batchInsert(users);
            service.batchInsert(inserts);
        }

        com.alibaba.fastjson.JSONObject data = new com.alibaba.fastjson.JSONObject();
        data.put("list", list);
        data.put("success", success);
        data.put("error", error);
        return data;
    }

}
